import request from "./utils/request";

// app.ts
App<IAppOption>({
  globalData: {
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
    token: '',
  },
  onLaunch(options:any) {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 检查用户是否已登录（是否有昵称）
    const nickname = wx.getStorageSync('userNickname');
    if (!nickname || !nickname.trim()) {
      // 未登录，提示用户去个人页面输入昵称
      wx.showModal({
        title: '提示',
        content: '请先前往个人页面输入昵称完成登录',
        showCancel: true,
        confirmText: '去设置',
        cancelText: '稍后',
        success: (res) => {
          if (res.confirm) {
            // 跳转到个人页面
            wx.switchTab({
              url: '/pages/oneself/oneself'
            });
          }
        }
      });
      return;
    }

    // 已登录，获取头像和 code 并发送登录请求
    const avatar = wx.getStorageSync('userAvatar') || '';
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log('获取到code:', res.code);
          if (this.loginWithNickname) {
            this.loginWithNickname(res.code, nickname.trim(), avatar);
          }
        } else {
          console.error('登录失败！' + res.errMsg);
        }
      },
      fail: (err) => {
        console.error('wx.login 调用失败', err);
      }
    });
    if (options.scene) {
      const scene = decodeURIComponent(options.scene);
      console.log('app，scene值:', scene);
    } else {
      // 正常进入
      console.log('正常进入页面');
    }
  },

  // 带昵称和头像的登录方法
  loginWithNickname(code: string, nickname: string, avatar: string = '') {
    wx.request({
      // url: 'http://192.168.2.11:8080/api/auth/loginWX', 
      url: 'https://tour.dwtcy.com.cn/api/auth/loginWX', 
      method: 'POST',
      data: {
        code: code,
        nickname: nickname,
        avatar: avatar
      },
      header:{
        'content-type': 'application/json'
      },
      success: (response) => {
        const data = response.data as{code:number,msg:string,data:{token:string,expireTime:number}};
        if(data && data.code===200){
          const token = data.data.token;
          const expireTime=data.data.expireTime;
          console.log('expireTime:',expireTime);
          console.log('token:',token);
          this.globalData.token = token 
          wx.setStorageSync('expireTime', expireTime)
          wx.setStorageSync('token', token)// 正确赋值到 globalData
          console.log('登录成功，昵称:', nickname, '头像:', avatar);
          
          // 检查是否有待处理的scene，如果有则进行绑定
          const pendingScene = wx.getStorageSync('pendingScene');
          if (pendingScene) {
            console.log('检测到待处理的scene，开始绑定:', pendingScene);
            request.bindSalesmanWXUser(pendingScene).then((res: any) => {
              if (res.code === 200) {
                console.log('绑定成功', res);
                // 清除已处理的scene
                wx.removeStorageSync('pendingScene');
              } else {
                console.error('绑定失败:', res.msg || '未知错误');
                wx.showToast({
                  title: res.msg || '绑定失败',
                  icon: 'none'
                });
              }
            }).catch(err => {
              console.error('绑定失败', err);
            });
          }
        } else {
          console.error('登录失败:', data.msg || '未知错误');
          wx.showToast({
            title: data.msg || '登录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('登录请求失败', err);
        wx.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      }
    });
  }
  
})